var BASE = BASE || {};

(function(context) {


    //////////////////////////////
    //create variables
    //////////////////////////////

    var camera, scene, renderer,
    mouseX = 0, mouseY = 0,
    particles = [];


    //////////////////////////////
    //public constructor function
    //////////////////////////////

    context.Starfield = function() {
        camera = new THREE.Camera(80, window.innerWidth/window.innerHeight, 1, 40000);
        camera.position.z = 1000;

        scene = new THREE.Scene();

        renderer = new THREE.CanvasRenderer();
        renderer.setSize( window.innerWidth, window.innerHeight );

        document.body.appendChild( renderer.domElement );

        makeParticles();

        document.addEventListener( "mousemove", onMouseMove, false );
        setInterval(update, 1000/30);
    };


    context.Starfield.prototype.getParticles = function() {
        console.log("particle count:", particles.length);
    };


    //////////////////////////////
    //private methods
    //////////////////////////////

    var update = function() {
        updateParticles();

        renderer.render( scene, camera );
    };

    var makeParticles = function() {
        var particle, material;

        for(var zpos= -1000; zpos < 1000; zpos+=20)
        {
            material = new THREE.ParticleCanvasMaterial( {color: 0xffffff, program: particleRender} );

            particle = new THREE.Particle(material);
            particle.position.x = randomRange(-500,500);
            particle.position.y = randomRange(-500,500);
            particle.position.z = zpos;
            particle.scale.x = particle.scale.y = 10;

            scene.addObject(particle);
            particles.push(particle);
        }
    };

    var particleRender = function(context) {
        context.beginPath();

        context.arc( 0, 0, 1, 0, Math.PI * 2, true );
        context.fill();
    };

    var updateParticles = function() {
        for(var i=0; i<particles.length; i++) {
            var particle = particles[i];
            particle.position.z += mouseY * 0.1;

            if(particle.position.z > 1000) particle.position.z -= 2000;
        }
    };
    var onMouseMove = function() {
        mouseX = event.clientX;
        mouseY = event.clientY;
    };

})(BASE);


//////////////////////////////
//global function
//////////////////////////////

function randomRange(min, max) {
	return Math.random() * (max-min) + min;
}
